/**
 * Created by wqz806687102 on 2016/1/11.
 */
'use strict';

angular.module('Query').controller('PostsRecordController', ['$scope', '$stateParams', 'BaseModule', 'BaseFunction', '$location', 'Authentication', 'BaseConst', 'BaseEnum', 'usbPort',

    function($scope, $stateParams, BaseModule, BaseFunction, $location, Authentication, BaseConst, BaseEnum, usbPort) {
        $scope.serachText;  //关键字
        $scope.IsDay = {
            Value: true
        };
        $scope.IsPeriod = {
            Value: false
        };
        $scope.StartDate = null;
        $scope.EndDate = null;

        usbPort.start();
        $scope.$on('usbPort.input', function(e, inputStr) {
            // $scope.btnQuery();
        });
        $scope.$on('$destroy', function() {
            usbPort.stop();
        });

        $scope.btnQuery = function(){
            if ($scope.serachText == undefined || $scope.serachText.trim() == "") {
                BaseFunction.alert('请输入员工卡号', '查询错误');
                return;
            };

            var startDate, endDate;
            if($scope.IsDay.Value){
                var nowDate = new Date();
                startDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0);
                endDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 1, 0, 0, 0);
            }
            else if($scope.IsPeriod.Value){
                if($scope.StartDate == null || (new Date($scope.StartDate)).getTime() == BaseConst.DateTime.Min.getTime()){
                    BaseFunction.alert('请输入开始日期', '查询错误');
                    return;
                }
                if($scope.EndDate == null || (new Date($scope.EndDate)).getTime() == BaseConst.DateTime.Min.getTime()){
                    BaseFunction.alert('请输入结束日期', '查询错误');
                    return;
                }

                $scope.StartDate = new Date($scope.StartDate);
                $scope.EndDate = new Date($scope.EndDate);
                startDate = new Date($scope.StartDate.getFullYear(), $scope.StartDate.getMonth(), $scope.StartDate.getDate(), 0, 0, 0);
                endDate = new Date($scope.EndDate.getFullYear(), $scope.EndDate.getMonth(), $scope.EndDate.getDate() + 1, 0, 0, 0);
                if(endDate.getTime() < startDate.getTime()){
                    BaseFunction.alert('开始日期不能大于结束日期', '查询错误');
                    return;
                }
            }
            queryByBarcode(startDate, endDate);
        }

        //按天
        $scope.chkByDay = function() { //当天查询
            $scope.IsDay.Value = true;
            $scope.IsPeriod.Value = false;
            $scope.IsDisplayPeriod = false;
        };
        $scope.IsDisplayPeriod = false;
        //按时间段
        $scope.chkByPeriod = function() { //时间段查询
            $scope.IsPeriod.Value = true;
            $scope.IsDisplayPeriod = true;
            $scope.IsDay.Value = false;

            if($scope.StartDate == null || (new Date($scope.StartDate)).getTime() == BaseConst.DateTime.Min.getTime()){
                $scope.StartDate = new Date();
            }
            if($scope.EndDate == null || (new Date($scope.EndDate)).getTime() == BaseConst.DateTime.Min.getTime()){
                $scope.EndDate = new Date();
            }
        };


        //初始化
        BaseModule.initModule($scope, 'Department');
        BaseModule.initModule($scope, 'User');
        BaseModule.initModule($scope, 'WorkLocation');
        BaseModule.initModule($scope, 'StationUser');
        BaseModule.initModule($scope, '_StationUser');

        $scope.Module.StationUser.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;
        $scope.Module.StationUser.PageSize = 15;

        $scope.Module._StationUser.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;
        $scope.Module._StationUser.PageSize = 15;

        $scope.Module.StationUser.Populate = [{
            path: 'WorkLocation',
            select: 'Code Name'
        }, {
            path: 'User',
            select: 'Code Name Department',
            populate: {
                path: 'Department',
                select: 'Code Name',
                model: 'Department'
            }
        }];

        $scope.Module.User.Populate = {
            path: 'Department',
            select: 'Code Name'
        };

        function getChildDepartmentIds(departmentIds, returnFun){
            $scope.Module.Department.find(
                {
                    ParentDepartment: {$in: departmentIds}
                },
                null, null, function(records){
                    var departments = [];
                    if(records.length > 0){
                        for(var i=0; i<records.length; i++){
                            departments.push(records[i]._id);
                        }
                    }
                    returnFun(departments);
                }
            );
        };

        function getAllChildDepartmentIds(departmentIds, returnFun){
            var returnAllIds = departmentIds;
            var resultFun = function(departIds){
                if(departIds.length > 0){
                    returnAllIds = returnAllIds.concat(departIds);
                    getChildDepartmentIds(departIds, resultFun);
                }
                else{
                    returnFun(returnAllIds);
                }
            }
            
            getChildDepartmentIds(departmentIds, resultFun);
        };

        //通过刷卡取数据
        function queryByBarcode(starttime, endtime) {
            //1.找当前人部门
            $scope.Module.User.find({UniqueID: $scope.serachText}, null, null, function(userRcds) {
                if (userRcds.length > 0) {
                    //2，如果当前人有下级部门，则根据当前人部门查所有下级部门
                    //负责查当前人部门所有上岗记录
                    getAllChildDepartmentIds([userRcds[0].Department], function(arrayId){
                        $scope.Module.WorkLocation.find(
                            {
                                Department: {$in: arrayId}
                            },
                            null, null, function(wRecords){
                                var wRecordIds = [];
                                if(wRecords.length > 0){
                                    for(var i=0; i<wRecords.length; i++){
                                        wRecordIds.push(wRecords[i]._id);
                                    }

                                    var stationCon = {
                                        $and: [
                                        {
                                            WorkLocation: {$in: wRecordIds},
                                        }, 
                                        {
                                            StartDateTime: {
                                                $gte: starttime
                                            }
                                        },
                                        {
                                            StartDateTime: {
                                                $lt: endtime
                                            }
                                        }]
                                    };

                                    //3，根据工位找到对应的上岗记录
                                    $scope.Module.StationUser.find(
                                        stationCon, 
                                        {                                            
                                            StartDateTime: 1
                                        },
                                        [{
                                            path: 'WorkLocation',
                                            select: 'Code Name'
                                        }, {
                                            path: 'User',
                                            select: 'Code Name Department',
                                            populate: {
                                                path: 'Department',
                                                select: 'Code Name',
                                                model: 'Department'
                                            }
                                        }], 
                                        function(suRecords){
                                            var dateMap = {};
                                            //4，用户的刷卡记录，去重，取最大
                                            for(var i=0; i<suRecords.length; i++){
                                                var strScanDate = new Date(suRecords[i].StartDateTime);
                                                strScanDate = strScanDate.getFullYear() + "." + (strScanDate.getMonth() + 1).toString() + "." + strScanDate.getDate();

                                                if(!dateMap[strScanDate]){
                                                    dateMap[strScanDate] = {};
                                                }
                                                var userMap = dateMap[strScanDate];
                                                if(userMap[suRecords[i].User._id]){
                                                    if(new Date(userMap[suRecords[i].User._id].StartDateTime).getTime() <
                                                        new Date(suRecords[i].StartDateTime).getTime()){
                                                        userMap[suRecords[i].User._id] = suRecords[i];
                                                    }
                                                }
                                                else{
                                                    userMap[suRecords[i].User._id] = suRecords[i];
                                                }
                                            }

                                            var displayRecords = [];
                                            angular.forEach(dateMap, function (userMap) {
                                                angular.forEach(userMap, function (suRecord) {
                                                    //该字段用来排序用，目前module.sort不支持多级排序
                                                    suRecord['_DepartmentName'] = suRecord.User.Department.Name;
                                                    displayRecords.push(suRecord);
                                                });
                                            });
                                            $scope.Module._StationUser.Records = displayRecords;
                                            $scope.Module._StationUser.sort({_DepartmentName: 1});
                                            $scope.Module._StationUser.emitOnLoadEvent();
                                        }
                                    );
                                }
                                else{
                                    $scope.Module._StationUser.Records = [];
                                    $scope.Module._StationUser.emitOnLoadEvent();

                                    //根据Barcode没找到用户
                                    BaseFunction.alert("用户的部门没有工位！", "提示");
                                }
                            }
                        );
                    });
                }
                else {
                    $scope.Module._StationUser.Records = [];
                    $scope.Module._StationUser.emitOnLoadEvent();

                    //根据Barcode没找到用户
                    BaseFunction.alert("没有找到该用户！", "提示");
                };
            });
        };

        //每人每天只取最早一条
        function getFirstRcd(rcds) {
            var rtnRcds = [];
            for (var i = 0; i < rcds.length; i++) {
                if (rtnRcds.length < 1) {
                    rtnRcds.push(rcds[i]);
                } else {
                    for (var j = 0; j < rtnRcds.length; j++) {
                        if (rcds[i].User.Code == rtnRcds[j].User.Code && compareDate(rcds[i].StartDateTime, rtnRcds[j].StartDateTime)) {
                            break;
                        } else {
                            if (j == rtnRcds.length - 1) {
                                rtnRcds.push(rcds[i]);
                            };
                        };
                    };
                };
            };
            return rtnRcds;
        };

        //比较两个日期是否为同一天
        function compareDate(date1, date2) {
            var str1 = new Date(date1).toDateString();
            var str2 = new Date(date2).toDateString();
            if (str1 == str2) {
                return true;
            } else {
                return false;
            };
        }

        //查询方法
        function query(starttime, endtime) {

            var searchText = {};
            searchText['Name'] = '/' + $scope.serachText + '/';

            //1.找部门
            $scope.Module.Department.find(searchText, null, null, function(dptsRcds) {
                var userCondition = {};
                if (dptsRcds.length > 0) {
                    //2.找到部门，用部门id+关键字找用户
                    var dptArr = [];
                    for (var i = 0; i < dptsRcds.length; i++) {
                        dptArr.push(dptsRcds[i]._id);
                    };
                    userCondition = {
                        $or: [{
                            Department: {
                                $in: dptArr
                            }
                        }, {
                            Name: '/' + $scope.serachText + '/'
                        }]
                    };
                } else {
                    //2.没找到部门，用关键字找用户
                    userCondition['Name'] = '/' + $scope.serachText + '/';
                }
                $scope.Module.User.find(userCondition, null, null, function(userRcds) {
                    if (userRcds.length > 0) {
                        //3.根据用户id找上下岗关系
                        var stationCon = {};
                        var userArr = [];
                        for (var i = 0; i < userRcds.length; i++) {
                            userArr.push(userRcds[i]._id);
                        };

                        if (starttime == undefined) { //无时间
                            stationCon = {
                                User: {
                                    $in: userArr
                                }
                            };
                        } else { //有时间
                            stationCon = {
                                $and: [{
                                    User: {
                                        $in: userArr
                                    }
                                }, {
                                    StartDateTime: {
                                        $gte: starttime
                                    }
                                }, {
                                    StartDateTime: {
                                        $lte: endtime
                                    }
                                }]
                            };
                        };

                        $scope.Module.StationUser.find(stationCon, null, $scope.Module.StationUser.Populate, function(stationRcds) {
                            if (stationRcds.length > 0) {
                                $scope.Module.StationUser.Records = stationRcds;
                            } else {
                                $scope.Module.StationUser.Records = [];
                            }
                            $scope.Module.StationUser.Condition = stationCon;
                            $scope.Module.StationUser.emitOnLoadEvent();
                        });
                    } else {
                        $scope.Module.StationUser.Records = [];
                        $scope.Module.StationUser.emitOnLoadEvent();
                    }
                });
            });
        }

        //计算当天起止时间
        function calCurrentDayTime() {
            var myDate = new Date();
            var rtnTime = myDate.toLocaleDateString();
            return rtnTime;
        };

        function getMonDayAndSunDay() {
            //datevalue = new Date();
            var now = new Date(); //当前日期 
            var nowYear = now.getYear();
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var nowMonth = now.getMonth() + 1;
            var dateValue = nowYear + "-" + nowMonth + "-" + now.getDate();
            var arr = dateValue.split("-");
            //月份-1 因为月份从0开始 构造一个Date对象  
            var date = new Date(arr[0], arr[1] - 1, arr[2]);

            var dateOfWeek = date.getDay(); //返回当前日期的在当前周的某一天（0～6--周日到周一）  

            var dateOfWeekInt = parseInt(dateOfWeek, 10); //转换为整型  

            if (dateOfWeekInt == 0) { //如果是周日  
                dateOfWeekInt = 7;
            }
            var aa = 7 - dateOfWeekInt; //当前于周末相差的天数  

            var temp2 = parseInt(arr[2], 10); //按10进制转换，以免遇到08和09的时候转换成0  
            var sunDay = temp2 + aa; //当前日期的周日的日期  
            var monDay = sunDay - 6 //当前日期的周一的日期  

            var startDate = new Date(arr[0], arr[1] - 1, monDay);
            var endDate = new Date(arr[0], arr[1] - 1, sunDay);

            var sm = parseInt(startDate.getMonth()) + 1; //月份+1 因为月份从0开始  
            var em = parseInt(endDate.getMonth()) + 1;

            //  alert("星期一的日期："+startDate.getYear()+"-"+sm+"-"+startDate.getDate());  
            //  alert("星期日的日期："+endDate.getYear()+"-"+em+"-"+endDate.getDate());  
            var start = nowYear + "\\" + sm + "\\" + startDate.getDate();
            var end = nowYear + "\\" + em + "\\" + endDate.getDate();
            var result = new Array();
            result.push(start);
            result.push(end);

            return result;
        }

        //计算本周起止时间
        function calCurrentWeekTime(isStartTime) {
            var now = new Date(); //当前日期 
            var nowDayOfWeek = now.getDay(); //今天本周的第几天 
            var nowDay = now.getDate(); //当前日 
            var nowMonth = now.getMonth(); //当前月 
            var nowYear = now.getYear(); //当前年 
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var rtnTime;
            if (isStartTime) { //返回起始时间
                var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
                rtnTime = formatDate(weekStartDate);
            } else { //返回终止时间
                var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1));
                rtnTime = formatDate(weekEndDate);
            };
            return rtnTime;
        }

        //计算本月起止时间
        function calCurrentMonthTime(isStartTime) {
            var now = new Date(); //当前日期 
            var nowMonth = now.getMonth(); //当前月 
            var nowYear = now.getYear(); //当前年 
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var rtnTime;
            if (isStartTime) { //返回起始时间
                var weekStartDate = new Date(nowYear, nowMonth, 1);
                rtnTime = formatDate(weekStartDate);
            } else { //返回终止时间
                //获取本月天数
                var monthStartDate = new Date(nowYear, nowMonth, 1);
                var monthEndDate = new Date(nowYear, nowMonth + 1, 1);
                var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);

                var weekEndDate = new Date(nowYear, nowMonth, days);
                rtnTime = formatDate(weekEndDate);
            };
            return rtnTime;
        }

        //格式化时间
        function formatDate(date) {
            var myyear = date.getFullYear();
            var mymonth = date.getMonth() + 1;
            var myweekday = date.getDate();
            return (myyear + "\\" + mymonth + "\\" + myweekday);
        }
    }
]);